<?php
defined('BASEPATH') or exit('No direct script access allowed');

//用户名正则，目前只支持邮箱
define('USERNAME_REG', '/^(?!\d+$)[\x{4e00}-\x{9fa5}a-z0-9]+_?[\x{4e00}-\x{9fa5}a-z0-9]+$/iu');
define('EMAIL_REG', '/^[a-z0-9_-]+@[a-z0-9_-]+(\.[a-z0-9_-]+)+$/i');

//(必须包含大小写字母和数字的组合，可以使用特殊字符，长度在6-30之间)
define('PASSWORD_REG', '/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,30}$/');
class Sign extends CI_Controller
{

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *         http://example.com/index.php/welcome
     *    - or -
     *         http://example.com/index.php/welcome/index
     *    - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    public function index()
    {
       
        //$this->load->view('welcome_message');
    }

    //注册页面
    public function register()
    {
        $DATA = array();
        //防止CSRF
        $DATA['csrf'] = array(
            'name' => $this->security->get_csrf_token_name(),
            'hash' => $this->security->get_csrf_hash(),
        );
        $this->load->view('register', $DATA);
    }

    //登录页面
    public function login()
    {
        $this->load->view('login');
    }

    //退出页面
    public function logout()
    {
        $this->load->view('home');
    }

    //注册表单提交页面
    public function signUp()
    {

        //设置时区为RPC
        date_default_timezone_set("PRC");


        $DATA = array();
        //获取去除空格后的登录用户名密码
        $username = trim($this->input->post('username'));
        $email = trim($this->input->post('email'));
        $password = trim($this->input->post('password'));

        //判断参数是否为空
        if (empty($username) || empty($email) || empty($password)) {
            //参数不合法
            $DATA['code'] = -3;
            $DATA['status'] = 'Invalid parameter';

        } else {

            //用户名和密码或昵称不符合规范
            if (!preg_match(USERNAME_REG, $username)
                || !preg_match(PASSWORD_REG, $password)
                || !preg_match(EMAIL_REG, $email)) {

                $DATA['code'] = -4;
                $DATA['status'] = 'Parameter format error';
            } else {

                //拼接查询字符串,查询用户名或者邮箱是否已经被注册
                $where = 'LOWER (`username`) = LOWER ("' . $username . '") OR LOWER (`email`) =LOWER ("' . $email . '")';

                $this->load->database();
                $this->db->select('username,email')
                    ->from('user_item_tb')
                    ->where($where);

                $recordRow = $this->db->get()->row();

                if ($recordRow) {
                    $DATA['code'] = -2;
                    $DATA['status'] = 'UserName or email has been taken';
                } else {
                    $passwordHash = password_hash($password, PASSWORD_DEFAULT);
                    $data = array(
                        //邮箱统一转为小写，用户名以提交的为准
                        'email' => strtolower($email),
                        'username' => $username,
                        'password' => $passwordHash,
                        'create_date' => date("Y-m-d H:i:s", Time()),
                    );

                    $this->db->insert('user_item_tb', $data);
                    $DATA['code'] = 1;
                    $DATA['status'] = 'Success';
                    $DATA['userId'] = $this->db->insert_id();

					self::sendMail(strtolower($email),$username);

                }
            }
        }

        $this->load->view('signup', $DATA);

    }

    //登录表单提交页面
    public function signIn()
    {
	
		

        $DATA = array();
        //获取去除空格后的登录邮箱用户名密码
        //$username = trim($this->input->post('username'));
        $email = trim($this->input->post('email'));
        $password = trim($this->input->post('password'));
		
		

        //判断参数是否为空
        if (empty($email) || empty($password)) {
            //参数不合法
            $DATA['code'] = -3;
            $DATA['status'] = 'Invalid parameter';
        } else {
            //邮箱和密码不符合规范
            if (!preg_match(EMAIL_REG, $email)
                || !preg_match(PASSWORD_REG, $password)) {

                $DATA['code'] = -4;
                $DATA['status'] = 'Invalid email or password';
            } else {

                $this->load->database();
                $row= $this->db->select('`uid`,`username`,`password`')
                    ->get_where('user_item_tb', array('email' => $email))
                    ->row_array();
                $passwordHash=$row['password'];
                $username=$row['username'];
                $uid=$row['uid'];
                //如果查询结果为空，用户不存在
                if (is_null($passwordHash)) {
                    $DATA['code'] = -2;
                    $DATA['status'] = 'Invalid username';
                } else {

                    //对密码hash进行校验
                    if (password_verify($password, $passwordHash)) {

						//使用自带的session机制
						if(!isset($_SESSION)){
							session_start();
						}
						
                        //session存储登录信息
                        $_SESSION['username'] = $username;
                        $_SESSION['email'] = $email;
                        $_SESSION['uid'] = $uid;
						
                        $DATA['code'] = 1;
                        $DATA['status'] = 'Success';
						

                    } else {
                        // Invalid 用户名密码不匹配
                        $DATA['code'] = -1;
                        $DATA['status'] = 'Incorrect username or password';
                    }
                }
            }
        }

        header('Location: /');

        //返回结果
        header('content-type:application/json;charset=utf-8');
        echo json_encode($DATA);
    }

    public function testMail() {
		$this->load->library('email');
        $config['protocol'] = 'smtp';
        $config['smtp_host'] = 'smtp.mailgun.org';
        $config['smtp_user'] = 'register@slideloop.com';
        $config['smtp_pass'] = 'www.slideloop.com';
        //$config['smtp_pass'] = 'qvb897214163';
        $config['smtp_port'] = 465;
        $config['smtp_crypto'] = 'ssl';
        //$config['mailpath'] = '/usr/sbin/sendmail';
        $config['charset'] = 'utf-8';
        $config['mailtype'] = 'html';
        $config['wordwrap'] = true;
        $config['crlf'] = "\r\n";
        $config['newline'] = "\r\n";
        $config['bcc_batch_mode'] = false;
        $config['bcc_batch_size'] = 200;

        $this->email->initialize($config);

        $this->email->from('register@slideloop.com', 'slideloop.com');
        $this->email->to('westooy@gmail.com');

        $this->email->subject('slideloop.com 账户激活验证邮件');
        $this->email->message('Hi,Thanks for using we have an up-to-date email address on file激活邮件');

        
		if($this->email->send(FALSE)){
			echo '发送成功';
		}else{
			echo '是吧';
			echo $this->email->print_debugger();
		}
		
   }
	

	private function sendMail($mail,$username)
    {
		
		
		//连接Redis,发送激活邮件
		$redis = new Redis();
		$redis->connect('localhost', 6379);
		
		//用邮箱和用户名生成一个激活码
		$activateCode=md5($mail.$username);
		//设置 redis 字符串数据
		$redis->set("slideloop:activateMail:{$activateCode}",'false');
		
		echo $redis->get("slideloop:activateMail:{$activateCode}");			
		
		
        $this->load->library('email');
        $config['protocol'] = 'smtp';
        $config['smtp_host'] = 'smtp.mailgun.org';
        $config['smtp_user'] = 'register@slideloop.com';
        $config['smtp_pass'] = 'www.slideloop.com';
        //$config['smtp_pass'] = 'qvb897214163';
        $config['smtp_port'] = 465;
        $config['smtp_crypto'] = 'ssl';
        //$config['mailpath'] = '/usr/sbin/sendmail';
        $config['charset'] = 'utf-8';
        $config['mailtype'] = 'html';
        $config['wordwrap'] = true;
        $config['crlf'] = "\r\n";
        $config['newline'] = "\r\n";
        $config['bcc_batch_mode'] = false;
        $config['bcc_batch_size'] = 200;

        $this->email->initialize($config);

        $this->email->from('register@slideloop.com', 'slideloop.com');
        $this->email->to('slideloop.com@gmail.com');

        $this->email->subject('slideloop.com 账户激活验证邮件');
        $this->email->message('Hi,Thanks for using we have an up-to-date email address on file.<a href="https://slideloop.com/active/'.$activateCode.'" target="_blank">激活邮件</a>');

        $this->email->send(FALSE);
		$this->email->print_debugger();
    }


	public function activate($token)
	{
		//token为空,错误
		if(empty($token)){
			return false;
		}


        $this->load->database();
        $this->db->select('username,email,expire_time')
            ->from('activate_item_tb')
            ->where('token',$token);

        $recordRow = $this->db->get()->row_array();
        //不存在的token记录
        if(!$recordRow){
        	echo 'Invalid token';
        	return false;
        }else{
        	var_dump(time());
        }


		//echo $token;
	}
}
